package com.gdziarmaga.webshop.web.managedBeans.client;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;

import org.springframework.beans.factory.annotation.Autowired;

import com.gdziarmaga.webshop.client.model.Client;
import com.gdziarmaga.webshop.client.services.ClientManager;
import com.gdziarmaga.webshop.utils.springcontext.AppContext;
import com.gdziarmaga.webshop.web.utils.FacesUtils;

@ManagedBean(name = "clientRegisterBean")
@ViewScoped
public class ClientRegisterBean {

	@Autowired
	private ClientManager clientManager;

	@PostConstruct
	public void init() {
		clientManager = (ClientManager) AppContext.getApplicationContext()
				.getBean("clientManager");
	}

	private Client client;

	public void createClient(ActionEvent event) {
		client.setFlag(1);
		clientManager.saveClient(client);
		client = null;
	}

	public Client getClient() {
		if (client == null) {

			if (((ClientLoginBean) FacesUtils.getRequest().getSession()
					.getAttribute("clientLoginBean")).isLogged()) {
				client = ((ClientLoginBean) FacesUtils.getRequest()
						.getSession().getAttribute("clientLoginBean"))
						.getClient();
			} else {
				client = new Client();
			}
		}
		return client;
	}

	public void setClient(Client client) {
		this.client = client;
	}

	public void createOrderClient(ActionEvent event) {
		client.setFlag(0);
		clientManager.saveClient(client);
		((BasketBean) FacesUtils.getRequest().getSession()
				.getAttribute("basketBean")).logTransactionToBase(client);

	}
}
